# -*- coding: utf-8 -*-
import urllib,urllib2,re,xbmcplugin,xbmcgui,sys,xbmc,xbmcaddon,xbmcvfs
import os,base64,time,HTMLParser,cookielib
import mechanize
from BeautifulSoup import BeautifulStoneSoup, BeautifulSoup, BeautifulSOAP as BS
import simplejson as json
from xml.dom.minidom import Document
import datetime

# -*- coding: iso-8859-9 -*-
SmartApp='aHR0cHM6Ly9zbWFydHVwaXB0di5nb29nbGVjb2RlLmNvbS9zdm4vdHJ1bmsvcGx1Z2luLnZpZGVvLkhGLlNtYXJ0QXBwL2NoYW5nZWxvZy50eHQ='
req = urllib2.Request(base64.b64decode(SmartApp))
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
response = urllib2.urlopen(req)
link=response.read()
response.close()
match10=re.compile('===(.*?)===').findall(link)
for SmartAppversiyon in match10:
    print SmartAppversiyon

__addon__ = xbmcaddon.Addon()
SmartAppversion = __addon__.getAddonInfo('version')
if SmartAppversion != SmartAppversiyon:
    dialog = xbmcgui.DialogProgress()
    dialog1 = xbmcgui.Dialog()
    dialog1.ok('[COLOR red][B]!!--Wrong Version!![/B][/COLOR]','[COLOR blue][B]Please Update Your Addon[/B][/COLOR]','[COLOR orange][B]Latest Version: [/B][/COLOR]'+'[COLOR green][B] '+SmartAppversiyon+'[/B][/COLOR]','[COLOR yellow][B]Your Addon Current Version: [/B][/COLOR]'+'[COLOR red][B]'+SmartAppversion+'[/B][/COLOR]')
    sys.exit()    
else:
    pass

#"special://home/addons/plugin.video.HF.SmartApp/resources/images/search.png")
__settings__ = xbmcaddon.Addon(id='plugin.video.HF.SmartApp')
__language__ = __settings__.getLocalizedString

home = __settings__.getAddonInfo('path')
icon = xbmc.translatePath( os.path.join( home, 'icon.png' ) )
fanart = xbmc.translatePath( os.path.join( home, 'fanart.jpg' ) )
folders = xbmc.translatePath(os.path.join(home, 'resources', 'lib'))
sys.path.append(folders)

xbmcPlayer = xbmc.Player()
playList = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)

grs='aHR0cDovL3V5ZWxpay5zbWFydGFwcHN0cmVhbS5jb20vd3AtbG9naW4ucGhw'
prf='aHR0cDovL3V5ZWxpay5zbWFydGFwcHN0cmVhbS5jb20vd3AtYWRtaW4vcHJvZmlsZS5waHA='

def CATEGORIES():
        login= __settings__.getSetting("login")
        password= __settings__.getSetting("password")
        if not login:
                __settings__.openSettings()
        else:
                pass
        from mechanize import Browser
        br = Browser()
        response = br.open(base64.b64decode(grs))
        br.select_form(nr=0)
        br.form['log']=__settings__.getSetting("login")
        br.form['pwd']=__settings__.getSetting("password")
        br.submit()
        response=br.open(base64.b64decode(prf))
        link=response.read()
        response.close()
        html2=br.response().read()
        if "Willkommen" in html2:
            print "basarili bir login yapildi"
            uyecheck=html2
            kullanici=login
            uyecheck=re.compile('<uyeler><kullanici><!\[CDATA\[(.*?)\]\]></kullanici><tarih><!\[CDATA\[(.*?)\]\]></tarih></uyeler>').findall(link)
            for uye,tarih in uyecheck:
                if kullanici == uye:
                    moment = datetime.datetime.today()
                    name='[COLOR yellow][B] Hosgeldin [COLOR violet] '+kullanici+' [COLOR tomato]Uyelik Bitis Tarihiniz: [COLOR red]'+str(tarih)
                    addDir('[COLOR blue][B] >> '+name+'[/B][/COLOR]',"","","special://home/addons/plugin.video.HF.SmartApp/fanart.jpg")
                    addDir('[COLOR blue][B] >> [COLOR lightgreen]Eklentiye Giris Zamani: [COLOR mintcream]'+ str(moment) +'[/B][/COLOR]',"","","special://home/addons/plugin.video.HF.SmartApp/fanart.jpg")
            html2=re.compile('<channel><title><!\[CDATA\[(.*?)\]\]></title><logo_30x30><!\[CDATA\[(.*?)\]\]></logo_30x30><description><!\[CDATA\[(.*?)\]\]></description><stream_url><!\[CDATA\[(.*?)\]\]></stream_url></channel>').findall(link)
            for name,resim,kat,url in html2:
                name='[COLOR yellow]'+kat+'[/COLOR] '+name
                addDir('[COLOR blue][B] >> [/B][/COLOR]'+name,url,2,resim)
        else:
            dialog = xbmcgui.DialogProgress()
            dialog1 = xbmcgui.Dialog()
            dialog1.ok('[COLOR red][B]Giris HATASI[/B][/COLOR]','[COLOR violet][B]Uyelikli ALAN..[COLOR yellow]Uyeliksiz Giris Yapamazsiniz.[/B][/COLOR]','[COLOR tomato][B]Uye iseniz, Kullanici Adi / Sifre nizi Kontrol Ediniz.[/B][/COLOR]')
            print 'Login Hata'
            __settings__.openSettings()
            return False  
############################################################################################################################################################################
#######################################################                   ##############################################################################
#######################################################                   ##############################################################################
############################################################################################################################################################################

def VideoLinks(name,url):
        xbmcPlayer = xbmc.Player()
        playList = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        playList.clear()
        
        addLink('Kanal Listesi << ','','')
        listitem = xbmcgui.ListItem(name)
        playList.add(url, listitem)
        xbmcPlayer.play(playList)
        exec_version = float(str(xbmc.getInfoLabel("System.BuildVersion"))[0:4])
        if exec_version < 14.0:
                log_path = xbmc.translatePath('special://logpath/xbmc.log')
                f = open(log_path,"r")
                strToSearch= ""
                for line in f:
                        
                        strToSearch +=line
                  

                patFinder1 = re.compile("http.+")
                patFinder2 = re.compile("rtmp.+")
                        

                findPat1 = re.findall(patFinder1,strToSearch)

                
                findPat2 = re.findall(patFinder2,strToSearch)
         

                for i in findPat1:
                                    
                        subFound = patFinder1.sub('', strToSearch)
                        

                        f=open(log_path ,"w")        
                        f.write(subFound)



                for b in findPat2:
                                    
                        subFound2 = patFinder2.sub('', strToSearch)
                        

                        f=open(log_path ,"w")                       
                        f.write(subFound2)

                f.flush()
                f.close()
        else:
                test='YWR2YW5jZWRzZXR0aW5ncy54bWw='
                nos='PGxvZ2xldmVsIGhpZGU9InRydWUiPi0xPC9sb2dsZXZlbD4='
                htmlp = HTMLParser.HTMLParser()
                pfile=xbmc.translatePath("special://home/userdata/")
                doc = Document()
                renk=doc.toprettyxml
                liste = doc.createElement("advancedsettings")
                doc.appendChild(liste)
                veri_ad = doc.createTextNode(base64.b64decode(nos))
                liste.appendChild(veri_ad)
                filepath = base64.b64decode(test)
                f = open(pfile+filepath, "w")
                f.write(htmlp.unescape(renk(indent="")))
############################################################################################################################################################################
############################################################################################################################################################################
############################################################################################################################################################################
############################################################################################################################################################################

def get_url(url):
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        link=link.replace('\xf6',"o").replace('&amp;',"&").replace('\xd6',"O").replace('\xfc',"u").replace('\xdd',"I").replace('\xfd',"i").replace('\xe7',"c").replace('\xde',"s").replace('\xfe',"s").replace('\xc7',"c").replace('\xf0',"g")
        link=link.replace('\xc5\x9f',"s").replace('&#038;',"&").replace('&#8217;',"'").replace('\xc3\xbc',"u").replace('\xc3\x87',"C").replace('\xc4\xb1',"?").replace('&#8211;',"-").replace('\xc3\xa7',"c").replace('\xc3\x96',"O").replace('\xc5\x9e',"S").replace('\xc3\xb6',"o").replace('\xc4\x9f',"g").replace('\xc4\xb0',"I").replace('\xe2\x80\x93',"-")
        response.close()
        return link

def addFolder(FILENAME, videoTitle, method, url="", thumbnail="",fanart=""):
        u = sys.argv[0]+"?fileName="+urllib.quote_plus(FILENAME)+"&videoTitle="+urllib.quote_plus(videoTitle)+"&method="+urllib.quote_plus(method)+"&url="+urllib.quote_plus(url)+"&fanart="+urllib.quote_plus(fanart)
        if thumbnail != "":
                thumbnail = os.path.join(IMAGES_PATH, thumbnail+".png")
        liz = xbmcgui.ListItem(videoTitle, iconImage="DefaultFolder.png", thumbnailImage=thumbnail)
        liz=xbmcgui.ListItem(videoTitle, iconImage="DefaultFolder.png", thumbnailImage=thumbnail)
        liz.setProperty( "Fanart_Image", fanart )
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
    

def addVideoLink(linkTitle, url, thumbnail=""):
    liz = xbmcgui.ListItem(linkTitle, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
    liz.setInfo(type="Video", infoLabels={"Title":linkTitle})
    liz.setProperty("IsPlayable", "true")
    xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=False)


def get_params():
    param=[]
    paramstring=sys.argv[2]
    if len(paramstring)>=2:
        params=sys.argv[2]
        cleanedparams=params.replace('?','')
        if (params[len(params)-1]=='/'):
            params=params[0:len(params)-2]
        pairsofparams=cleanedparams.split('&')
        param={}
        for i in range(len(pairsofparams)):
            splitparams={}
            splitparams=pairsofparams[i].split('=')
            if (len(splitparams))==2:
                param[splitparams[0]]=splitparams[1]
    return param

def addLink(name,url,iconimage):
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
        return ok


def addDir(name,url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
        
              
params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

if mode==None or url==None or len(url)<1:
        CATEGORIES()

elif mode==2:
        VideoLinks(name,url)
               
xbmcplugin.endOfDirectory(int(sys.argv[1]))
